package com.cloudkinto.appletservice.orderback.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.appletservice.orderback.AppletOrderBackService;
import com.cloudkinto.appletservice.orderback.vo.AppletOrderBackDetailRes;
import com.cloudkinto.appletservice.orderback.vo.AppletOrderBackPageRes;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.dao.DicBusinessItemDao;
import com.cloudkinto.dao.OrderBackDao;
import com.cloudkinto.entity.DicBusinessItemDo;
import com.cloudkinto.entity.OrderBackDo;
import com.cloudkinto.entity.ShopDo;
import com.cloudkinto.entity.StorageDo;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.orderback.vo.OrderBackCustomerProcessingReq;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.storage.StorageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Author Administrator
 *
 * @Des
 * @Version
 * @Date 2020/11/24
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class AppletOrderBackServiceImpl extends ServiceImpl<OrderBackDao, OrderBackDo> implements AppletOrderBackService {
    @Autowired
    private OrderBackDao dao;
    @Autowired
    private FileService fileService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private StorageService storageService;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;

    @Override
    public AppletOrderBackDetailRes detail(Long id) {
        OrderBackDo entityDo = dao.selectById(id);
        AppletOrderBackDetailRes res = new AppletOrderBackDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        res.setFileId(entityDo.getFileId());
        res.setFileUrl(fileService.getFilePath(entityDo.getFileId()));
        ShopDo shopDo = shopService.getBaseMapper().selectById(entityDo.getShopId());
        if (shopDo != null) {
            res.setShopName(shopDo.getShopName());
        }
        StorageDo storageDo = storageService.getBaseMapper().selectById(entityDo.getStorageId());
        if (storageDo != null) {
            res.setStorageName(storageDo.getStorageName());
        }
        DicBusinessItemDo status = dicBusinessItemDao.selectById(entityDo.getStatus());
        if (status != null) {
            res.setStatus(status.getDicItemValue());
        }
        DicBusinessItemDo backResult = dicBusinessItemDao.selectById(entityDo.getBackResult());
        if (backResult != null) {
            res.setBackResult(backResult.getDicItemValue());
        }
//        List<OrderBackDetailItem> items = new ArrayList<>();
//        LambdaQueryWrapper<OrderBackProductDo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(OrderBackProductDo::getOrderId, id);
//        List<OrderBackProductDo> orderBackProductDos = orderBackProductDao.selectList(wrapper);
//        for (OrderBackProductDo orderBackProductDo : orderBackProductDos) {
//            OrderBackDetailItem item = new OrderBackDetailItem();
//            item.setCount(orderBackProductDo.getCount());
//            ProductInfoDo productInfoDo = productInfoDao.selectById(orderBackProductDo.getProductId());
//            if (productInfoDo != null) {
//                item.setProductId(productInfoDo.getId());
//                item.setProductName(productInfoDo.getProductName());
//                item.setSku(productInfoDo.getCommoditySku());
//            }
//            items.add(item);
//        }

//        res.setItems(items);
        return res;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<OrderBackDo> wrapper = queryBuild(map);
        IPage<OrderBackDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<AppletOrderBackPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    private IPage<OrderBackDo> pageInit(Map<String, String> map) {
        IPage<OrderBackDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    //查询分页列表之后对列表数据的处理
    private List<AppletOrderBackPageRes> handlerListAfter(List<OrderBackDo> list) {
        List<AppletOrderBackPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(orderBackDo -> {
                AppletOrderBackPageRes res = new AppletOrderBackPageRes();
                BeanUtils.copyProperties(orderBackDo, res);
                ShopDo shopDo = shopService.getBaseMapper().selectById(orderBackDo.getShopId());
                if (shopDo != null) {
                    res.setShopName(shopDo.getShopName());
                }
                StorageDo storageDo = storageService.getBaseMapper().selectById(orderBackDo.getStorageId());
                if (storageDo != null) {
                    res.setStorageName(storageDo.getStorageName());
                }
                DicBusinessItemDo status = dicBusinessItemDao.selectById(orderBackDo.getStatus());
                if (status != null) {
                    res.setStatus(status.getDicItemValue());
                }
                DicBusinessItemDo backResult = dicBusinessItemDao.selectById(orderBackDo.getBackResult());
                if (backResult != null) {
                    res.setBackResult(backResult.getDicItemValue());
                }
                res.setOperateFee((orderBackDo.getOperateFee() == null ? 0 : orderBackDo.getOperateFee())
                        + (orderBackDo.getTaxFee() == null ? 0 : orderBackDo.getTaxFee()) + (res.getShipFee() == null ? 0 : res.getShipFee()));
                result.add(res);
            });
        }
        return result;
    }

    private QueryWrapper<OrderBackDo> queryBuild(Map<String, String> map) {
        QueryWrapper<OrderBackDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("order_out_number", map.get("keyword")).or();
            wrapper.like("contact_name", map.get("keyword")).or();
            wrapper.like("track_number", map.get("keyword"));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("company_id", map.get("companyId"));
        }
        if (StringUtils.isNotBlank(map.get("shopId"))) {
            wrapper.eq("shop_id", map.get("shopId"));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("result"))) {
            wrapper.eq("back_result", map.get("result"));
        }
        return wrapper.orderByDesc("id");
    }

    @Override
    public void customerProcessing(OrderBackCustomerProcessingReq req, Long userId, Long companyId) {
        OrderBackDo orderBackDo = dao.selectById(req.getId());
        if (orderBackDo == null || orderBackDo.getStatus() > DicBusinessItemConstant.orderBackInstructions) {
            throw new BizExceptionI18("order.has.resolved");
        }
        orderBackDo.setTips(req.getTips());
        if (req.getOperate() == 1) {//上架
            handlerPutaway(req, userId, orderBackDo);
        } else if (req.getOperate() == 2) {//废弃
            handlerAbandon(req, userId, orderBackDo);
        }
    }

    private void handlerAbandon(OrderBackCustomerProcessingReq req, Long userId, OrderBackDo orderBackDo) {
        orderBackDo.setUpdateBy(userId);
        orderBackDo.setUpdateTime(new Date());
        orderBackDo.setBackResult(DicBusinessItemConstant.orderBackAbandon);
        orderBackDo.setStatus(DicBusinessItemConstant.orderBackInstructions);
        dao.updateById(orderBackDo);
    }

    private void handlerPutaway(OrderBackCustomerProcessingReq req, Long userId, OrderBackDo orderBackDo) {
        orderBackDo.setUpdateBy(userId);
        orderBackDo.setUpdateTime(new Date());
        orderBackDo.setBackResult(DicBusinessItemConstant.orderBackPutAway);
        orderBackDo.setStatus(DicBusinessItemConstant.orderBackInstructions);
        dao.updateById(orderBackDo);
    }
}
